<template>
    <el-dropdown trigger="click" @visible-change="visibleChange" class="block-dropdown" :hide-on-click="true" :disabled="disabled">
        <!--  多选框内容 -->
        <div v-if="multiple" class="el-select el-select--small">
            <div class="el-select__tags" ref="el_select__tags" style="width: 100%; padding-right:35px;">
                <span>
                    <span v-for="(item,index) in multipleValue" class="el-tag el-tag--info el-tag--mini el-tag--light">
                        <span class="el-select__tags-text">{{ item.userName }}</span>
                        <i class="el-tag__close el-icon-close" @click.stop="remove(item,index)"  v-if="!disabled"></i>
                    </span>
                </span>
            </div>
            <div class="el-input el-input--small el-input--suffix">
                <input type="text" readonly="readonly" autocomplete="off" :placeholder="multipleValue.length>0?'':'请选择'" class="el-input__inner" :style="{height: inputHeight + 'px'}">
                <span class="el-input__suffix">
                    <span class="el-input__suffix-inner">
                        <i class="el-select__caret el-input__icon el-icon-arrow-up"></i>
                    </span>
                </span>
            </div>
        </div>
        <!--  单选框内容 -->
        <div v-else data-v-d3f53d98="" class="el-select el-select--small">
            <div class="el-input el-input--small el-input--suffix">
                <input type="text" readonly="readonly" v-model="singleValue.userName" autocomplete="off" placeholder="请选择" class="el-input__inner">
                <span class="el-input__suffix">
                    <span class="el-input__suffix-inner">
                        <i class="el-select__caret el-input__icon el-icon-arrow-up"></i>
                    </span>
                </span>
            </div>
        </div>
        <el-dropdown-menu slot="dropdown" class="person-drop-menu">
            <el-dropdown-item v-show="false" ref="dropdownItem" />
            <div size="small" style="margin-left:0;margin-bottom:10px;">
                <div class="query-param">

                    <el-input style="width: 270px" class="query-input" size="small" placeholder="请输入" v-model="key">
                        <template slot="append">
                            <i class="el-icon-search"></i>
                            <span @click="getList(key)">搜索</span>
                        </template>
                    </el-input>
                </div>
            </div>
            <el-table ref="table" :data="tableData" :row-class-name="'el-dropdown-menu__item'" @row-click="rowClick" @selection-change="selectionChange" max-height="350" border style="width:500px">
                <el-table-column v-if="multiple" type="selection" width="55" align="center" />
                <el-table-column :label="$t('public.serialNum')" type="index" align="center">
                    <template slot-scope="scope">
                        {{(currentPage - 1) * currentSize + scope.$index + 1}}
                    </template>
                </el-table-column>
                <el-table-column prop="userName" label="姓名" show-overflow-tooltip width="100">
                </el-table-column>
                <el-table-column prop="dept.deptName" label="部门" show-overflow-tooltip width="100">
                </el-table-column>
                <el-table-column prop="email" show-overflow-tooltip label="邮箱">
                </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[4, 10, 20, 40]" :page-size="currentSize" :small="true" style="text-align: right;margin:8px 0 0;" layout="total,  prev, pager, next, sizes" :total="total">
            </el-pagination>

        </el-dropdown-menu>
    </el-dropdown>

</template>
<script>
/**
 * 人员多选下拉组件
 * author: fenghuan@enjoysoftware.cn
 * date: 2022/02/16
 * use: <enjoy-person-dropdown v-model="persons"> </enjoy-person-dropdown>
 * person: [{id:1,name:'张三'}, ...]
 */
import { listUser } from '@/api/system/user'
import { find, forEach } from 'lodash'
export default {
    name: 'EnjoySelectUser',
    props: {
        /** 外部v-model传入的人员 例如：多选：v-model=[{id:1,name:'张三'}] 单选：v-model= {id:1,name:'张三'}*/
        value: {
            default: undefined,
        },
        /** 多选 默认不传为单选 */
        multiple: {
            type: Boolean,
        },
        deptId: {
            type: String,
        },
        disabled:{
            type: Boolean,
            default:false
        }
    },
    computed: {
        /** 多选值 [{userId:1,userName:'张三'},...] */
        multipleValue() {
            let multipleValue = []
            if (
                this.multiple &&
                Array.isArray(this.value) &&
                this.value.length > 0
            ) {
                forEach(this.value, (value, key) => {
                    multipleValue.push({
                        userId: value.id,
                        userName: value.name,
                    })
                })
            }
            return multipleValue
        },
        singleValue() {
            /** 单选 {userId:... userName:...} */
            let singleValue = {}
            if (!this.multiple && this.value) {
                const { id, name } = this.value
                if (id && name) {
                    singleValue = { userId: id, userName: name }
                }
            }
            return singleValue
        },
    },
    data() {
        return {
            total: 0, // 表格数据总数
            tableData: [], // 表格数据
            currentPage: 1, //表格当前页数
            currentSize: 4, //表格当前页面数数据数
            inputHeight: 32, //输入框高度
            key: '',
        }
    },
    mounted() {
        this.init()
    },
    methods: {
        init() {
            if (this.multiple) {
                const self = this
                /*多选时监听文本框内容高度*/
                const observer = new ResizeObserver((entries) => {
                    entries.forEach((entry) => {
                        const cr = entry.contentRect
                        self.inputHeight = (cr.height || 24) + 8
                    })
                })
                observer.observe(self.$refs.el_select__tags)
            }
        },
        visibleChange(visible) {
            
            if (visible) {
                this.getList()
            }
        },

        getList(userName) {
            const self = this
            listUser({
                pageNum: this.currentPage,
                pageSize: this.currentSize,
                userName: userName,
                deptId: this.deptId,
            }).then((response) => {
                this.tableData = response.rows
                this.total = response.total
                this.$nextTick(function () {
                    this.multiple &&
                        self.multipleValue.forEach((row, index) => {
                            const tableRow = find(
                                this.tableData,
                                (o) => o.userId == row.userId
                            )
                            self.$refs.table.toggleRowSelection(tableRow || row)
                        })
                })
            })
        },
        rowClick(row, column, event) {
            const { multiple } = this
            if (multiple) {
                /* 多选 */
                this.$refs.table.toggleRowSelection(row)
            } else {
                /* 单选 */
                this.$emit('input', { name: row.userName, id: row.userId })
                this.$emit('change', {
                    name: row.userName,
                    id: row.userId,
                    deptName: row.deptName,
                    deptId: row.deptId,
                })
                this.$refs.dropdownItem.$el.click()
            }
        },
        selectionChange(selection) {
            this.$nextTick(function () {
                this.$emit('input', this.exportData(selection))
            })
        },
        handleSizeChange(size) {
            this.currentSize = size
            this.getList()
        },
        handleCurrentChange(page) {
            this.currentPage = page
            this.getList()
        },
        remove(row, index) {
            const multipleValue = [...this.multipleValue]
            multipleValue.splice(index, 1)
            const tableRow = find(this.tableData, row)
            this.$refs.table.toggleRowSelection(tableRow, false)
            this.$emit('input', this.exportData(multipleValue))
        },
        /* 输出外部的数据，例如：[{id:1,name:'张三'}] */
        exportData(data) {
            let array = []
            if (Array.isArray(data)) {
                forEach(data, (value, key) => {
                    array.push({ id: value.userId, name: value.userName })
                })
            }
            return array
        },
    },
}
</script>

<style scoped>
.block-dropdown {
    display: block;
}
::v-deep .el-pagination__sizes {
    margin: 0;
}
::v-deep .el-pagination--small .btn-prev,
::v-deep .el-pagination--small .el-pager,
::v-deep .el-pagination--small .btn-next {
    margin-top: 2px;
}
.person-drop-menu {
    padding: 8px;
}
::v-deep .el-dropdown,
::v-deep .el-select {
    display: block;
}

.query-param {
    display: flex;
    width: 100%;
}
.query-input {
    color: white;
}
::v-deep .el-input-group__append,
.el-input-group__prepend {
    background-color: var(--current-color);
    color: white;
    cursor: pointer;
}
</style>
